package com.mengwen.backstage.controller;


import com.mengwen.backstage.config.WeChatConfig;
import com.mengwen.backstage.pojo.Partner;
import com.mengwen.backstage.service.AdminService;
import com.mengwen.backstage.service.PartnerService;
import com.mengwen.backstage.util.JwtUtil;
import com.mengwen.backstage.util.WeixinUtil;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 微信授权登录
 */
@Controller
@RequestMapping("/")
public class WeChatOauth {
    private static final Log LOG = LogFactory.getLog(WeChatOauth.class);


    @Autowired
    WeChatConfig weChatConfig;

    @Autowired
    PartnerService partnerService;

    @Autowired
    AdminService adminService;

    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 微信授权请求
     * @param response
     * @throws IOException
     */
    @RequestMapping("mengwen/oauth/user_info")
    public void oauthUserInfo(HttpServletResponse response) throws IOException {

        String redirectUri = weChatConfig.getWxOaRedirectUrl() + weChatConfig.getWxOauthRedirectUri();

        redirectUri = URLEncoder.encode(redirectUri,"UTF-8");

        String url = weChatConfig.getWxOauthRequestUrl()
        .replace("APPID",weChatConfig.getAppId())
        .replace("REDIRECT_URI",redirectUri)
        .replace("SCOPE","snsapi_userinfo")
        .replace("STATE","mwoauth");

        response.sendRedirect(url);


    }


    /**
     * 微信授权回调
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("mengwen/user_info/invoke")
    public String aouthUserInfoInvoke(HttpServletRequest request, Model model){


        String code = request.getParameter("code");

        String url = weChatConfig.getWxOauthGetOpenidAndAccessTokenUrl()
                .replace("APPID",weChatConfig.getAppId())
                .replace("SECRET",weChatConfig.getAppsecret())
                .replace("CODE",code);

        // 获取access_token和openid
        JSONObject accessTokenAndOpenidjson = WeixinUtil.httpRequest(url, "POST", null);

        // 打印授权的用户信息：
        LOG.info("有人授权，打印授权信息：");
        LOG.info(accessTokenAndOpenidjson.toString());

        // 获取用户信息：
        String getUserInfoUrl = weChatConfig.getWxOauthGetUserInfoByOpenidAndAccessTokenUrl()
                .replace("ACCESS_TOKEN",accessTokenAndOpenidjson.getString("access_token"))
                .replace("OPENID",accessTokenAndOpenidjson.getString("openid"));


        JSONObject userInfoJson = WeixinUtil.httpRequest(getUserInfoUrl, "GET", null);
        String openid = userInfoJson.getString("openid");
        LOG.info("openid:" + openid);

        Partner partner = partnerService.findByOpenid(openid);
        if (partner != null) {// 查询是合伙人
            LOG.info("合伙人：" + partner.getNickname() + "登录，openid:" + partner.getOpenid());
            Integer state = partnerService.findStateByOpenid(openid);
            model.addAttribute("partner",partner);
            // 分发jwttoken
            String partnerToken = JwtUtil.genePartnerJsonWebToken(partner);
            // System.out.println(partnerToken);
            model.addAttribute("partnerToken",partnerToken);
            if (state == 1 ) { // 已完成首次登录，直接跳转页面
                return "partner_page";
            }else {//未完成首次登录，跳转登录页
                // partnerService.updateStateByOpenid(openid);
                return "login_door";
            }

        }else {// 是管理员，密码登录
            LOG.info("有人"   + "要登录，openid:" + openid);
            return "login_door";
        }



    }






}
